package Server;

import java.io.DataInputStream;
import java.io.IOException;

import javax.swing.JTextArea;

/**
 * SReceiver
 * me
 * Thread for reading socket information
 * @author Yaxing Chen
 *
 */
class ServerReceiver extends Thread{
	private String separator = ">>><<<";
    private DataInputStream dis;
    private JTextArea area;
    private int identify; //0: server, 1: clients
    private int id; //id #
    
  //mediator pattern
    private ClientMediator mediator;
    
    public ServerReceiver(DataInputStream d,JTextArea a, int id, int idNum){
        this.dis = d;
        this.area = a;
        this.identify = id;
        this.id = idNum;
        mediator = Server.getMediator();
    }
    
    public void run(){
        String s;
        String input;
        String toServer;
        String toClient;
        while(true){
            try{
            	if(dis == null){
            		break;
            	}
            	input = dis.readUTF();
            	
               	if(input.equals("__ID")){
               		mediator.assignClientID(id);
                	area.append("New client: " + id +"\n");
                	area.append("Clients Qty:" + mediator.getUserQty() + "\n");
                	continue;
                }
                	
               	toServer = "From client# " + id + ":" + input;
               	area.append(toServer);
	            
               	toClient = id + separator + input;
               	
              //broadcast it to every client
               	mediator.sendToAll(id, toClient);
                
               	if(input.equals("bye")){
                    dis.close();
                    area.setText("Client #"+id+" Exit!");
                    break;
                } 
            }catch(IOException e){
                e.printStackTrace();
                break;
            }
        }
    }
}